package cn.suzhang.jsharp.common.config.data;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * 数据源配置
 * 
 * @author zhangsu
 * @since 2018-02-15
 */
@Configuration
public class DataSourceConfig {

    /**
     * sys数据源配置
     * 
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.sys")
    public DataSource sysDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.book")
    public DataSource bookDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "userJdbcTemplate")
    public JdbcTemplate primaryJdbcTemplate(@Qualifier("sysDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public PlatformTransactionManager userTransactionManager(@Qualifier("sysDataSource") DataSource sysDataSource) {
        return new DataSourceTransactionManager(sysDataSource);
    }

    @Bean(name = "bookJdbcTemplate")
    public JdbcTemplate secondaryJdbcTemplate(@Qualifier("bookDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
